package com.lagou.rpc.provider;

import com.lagou.rpc.provider.server.RpcServer;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.nio.charset.StandardCharsets;

@SpringBootApplication
public class ServerBootstrapApplication implements CommandLineRunner {

	@Value("${netty.port}")
	private int port;

	@Autowired
	RpcServer rpcServer;

	private CuratorFramework client;

	public static void main(String[] args) {
		SpringApplication.run(ServerBootstrapApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {

		new Thread(new Runnable() {
			@Override
			public void run() {
				String host = "127.0.0.1";

				rpcServer.startServer(host, port);
			}
		}).start();

		// 启动服务注册
//		client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(1000, 2));
		client = CuratorFrameworkFactory.builder().connectString("localhost:2181")
				.retryPolicy(new ExponentialBackoffRetry(1000, 2))
				.sessionTimeoutMs(2000).connectionTimeoutMs(4000).build();
		client.start();

		registerServer();
	}

	private void registerServer() throws Exception {
		String path = "/server-registry/localhost:" + port;
		client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, (System.currentTimeMillis() + ":" + 0).getBytes(StandardCharsets.UTF_8));
	}
}
